package com.example.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;

@Configuration
@ConditionalOnClass(value = {JedisCluster.class})
@EnableConfigurationProperties(RedisProperties.class)
public class JedisClusterConfig {

    @Autowired
    private JedisClusterProperties jedisClusterProperties;

    private GenericObjectPoolConfig getPoolConfig(){
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        RedisProperties.Pool redisPropertiesPool = jedisClusterProperties.getPool();
        poolConfig.setMaxIdle(redisPropertiesPool.getMaxIdle());
        poolConfig.setMinIdle(redisPropertiesPool.getMinIdle());
        poolConfig.setMaxTotal(redisPropertiesPool.getMaxActive());
        poolConfig.setMaxWaitMillis(redisPropertiesPool.getMaxWait());
        return poolConfig;
    }

    @Bean
    @Scope("singleton")
    public JedisCluster getJredisCluster() {
        JedisClusterProperties.Cluster redisPropertiesCluster = jedisClusterProperties.getCluster();
        HashSet<HostAndPort> nodes = new HashSet<>();
        for (String nodeStr :
                redisPropertiesCluster.getNodes()) {
            nodes.add(HostAndPort.parseString(nodeStr));
        }
        return new JedisCluster(nodes,
                redisPropertiesCluster.getConnectionTimeout(),
                redisPropertiesCluster.getSoTimeout(),
                redisPropertiesCluster.getMaxRedirects(),
                getPoolConfig());
    }
}
